<template>
  <div class="upload-wrapper">
    <div class="tabs">
      <div
        class="tab-item"
        :class="index === activeTab ? 'active' : ''"
        v-for="(item, index) in tabList"
        :key="index"
        @click="handleChangeTab(index)"
      >
        <el-icon size="20" v-if="index === 0" style="margin-right: 20px"
          ><DocumentAdd
        /></el-icon>
        <el-icon size="20" v-if="index === 1" style="margin-right: 20px"
          ><Edit
        /></el-icon>
        <span>{{ item }}</span>
      </div>
    </div>
    <div class="upload-type">
      <div v-if="activeTab === 0" style="height: 90%">
        <el-upload
          class="upload-demo"
          drag
          :action="actionURL"
          :show-file-list="false"
          name="files"
          enctype="multipart/form-data"
          :before-upload="beforeUploadFile"
          :on-success="handleUploadSuccess"
          :on-exceed="handleExceed"
          accept=".pdf,.txt,.doc,.docx"
          style="height: 100%"
          :limit="1"
          ref="upload"
        >
          <div style="display: flex; justify-content: space-evenly">
            <el-icon color="#0f90e3" size="64">
              <Word />
            </el-icon>
            <el-icon color="#dc2e1b" size="64">
              <Pdf />
            </el-icon>
            <el-icon class="doc-theme-color" size="64">
              <Txt />
            </el-icon>
          </div>
          <div class="el-upload__text" style="color: #aaa; font-size: 12px">
            建议上传5000字以内的纯文字文档，字数过多以及包含图片、表格等情况都会
            影响生成效果
          </div>
          <template #tip>
            <div class="el-upload__tip" style="color: red; padding-left: 20px">
              doc,pdf 文件大小不能超过2MB, txt 文件不能超过200KB,限制单个文件
            </div>
          </template>
        </el-upload>
        <div class="file-list">
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 0 8px;
            "
            class="file"
            v-for="item in fileList"
            :key="item.file_id"
          >
            <div>
              <el-icon><Document /></el-icon> {{ item.name }}
            </div>
            <el-icon color="red" @click="deletedFile(item)"><Close /></el-icon>
          </div>
        </div>
      </div>
      <div v-else-if="activeTab === 1" style="height: 100%">
        <el-input
          v-model="inputValue"
          style="width: 100%; height: 100%"
          maxlength="5000"
          type="textarea"
          placeholder="请输入内容..."
          show-word-limit
          :input-style="{ height: '100%' }"
          resize="none"
        />
      </div>
    </div>
    <div
      class="footer"
      style="
        display: flex;
        justify-content: flex-end;
        padding: 0 10px;
        margin-top: 10px;
        height: 30px;
      "
    >
      <el-button type="warning" @click="onConfirm">确定</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { nextTick, ref, type Ref, onMounted, defineEmits } from 'vue'
import { ElMessage, type UploadProps, genFileId } from 'element-plus'
import { deleteFile } from '@/api/file.js'
import Word from '@/icons/Word.vue'
import Pdf from '@/icons/Pdf.vue'
import Txt from '@/icons/Txt.vue'
import type { UploadInstance, UploadRawFile } from 'element-plus'
import { Close, DocumentAdd, Edit } from '@element-plus/icons-vue'
import { pptFileContentKey, pptFileIdKey, pptOutlineKey, pptThemeInputKey } from '@/views/ai-pptx/ppt-helpers'
import { UploadFileItem } from '@/models/ai-ppt'
const actionURL = import.meta.env.VITE_BASE_API + '/upload/files'
const inputValue = ref<string>('')
const activeTab = ref<number>(0)
const tabList = ['文件上传', '自由输入']
const fileList: Ref<UploadFileItem[]> = ref([])
const upload = ref<UploadInstance>()

const emit = defineEmits(['onSend'])

onMounted(() => {
  const fileContent = window.sessionStorage.getItem(pptFileContentKey.value)
  const fileId = window.sessionStorage.getItem(pptFileIdKey.value)
  if (fileContent) {
    window.sessionStorage.removeItem(pptFileIdKey.value)
    inputValue.value = fileContent
    activeTab.value = 1
  } else if (fileId) {
    fileList.value = JSON.parse(fileId)
    activeTab.value = 0
  }
})

const handleChangeTab = (index: number) => {
  if (activeTab.value === index) return
  activeTab.value = index
  fileList.value = []
  nextTick(() => {
    upload.value && upload.value!.clearFiles()
  })
  inputValue.value = ''
}
const beforeUploadFile: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    ![
      'application/pdf',
      'text/plain',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    ].includes(rawFile.type)
  ) {
    ElMessage.error('格式不正确!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文档文件大小不能超过2MB!')
    return false
  } else if (rawFile.type === 'rawFile.type' && rawFile.size > 1024 * 200) {
    ElMessage.error('文本文件大小不能超过200KB!')
    return false
  }
  return true
}
const handleUploadSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  if (response.code === 200) {
    fileList.value.push({
      name: uploadFile.name,
      file_id: response.data.list[0]?.file_id,
    })
  }
}
const handleExceed: UploadProps['onExceed'] = async (files) => {
  upload.value!.clearFiles()
  await deletedFile(fileList.value[0])
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  upload.value!.submit()
}
const deletedFile = async (item) => {
  try {
    const res = await deleteFile(item.file_id)
    if (res) {
      fileList.value = []
      upload.value!.clearFiles()
    }
  } catch (error) {
    console.log('error', error)
  }
}

const onConfirm = () => {
  if (fileList.value.length === 0 && !inputValue.value.trim()) {
    return
  }
  if (activeTab.value === 0) {
    window.sessionStorage.setItem(pptFileIdKey.value, JSON.stringify(fileList.value))
    window.sessionStorage.removeItem(pptFileContentKey.value)
  } else {
    window.sessionStorage.setItem(pptFileContentKey.value, inputValue.value)
    window.sessionStorage.removeItem(pptFileIdKey.value)
  }
  window.sessionStorage.removeItem(pptThemeInputKey.value)
  window.sessionStorage.removeItem(pptOutlineKey.value)
  emit('onSend')
}
</script>
<style scoped lang="scss">
.upload-wrapper {
  height: 400px;
  width: calc(100% - 80px);
  max-width: 1000px;
  box-shadow: var(--el-box-shadow);
  background: #fff;
  display: flex;
  flex-direction: column;
  margin: 0 auto;
  border-radius: 8px;
  overflow: hidden;
  padding-bottom: 20px;
  .active {
    color: $color-ppt-theme;
    background: rgba($color-ppt-theme, 0.1) !important;
  }
  .tabs {
    height: 50px;
    display: flex;
    .tab-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      &:hover {
        color: $color-ppt-theme;
      }
    }
  }
  .upload-type {
    height: calc(100% - 100px);
    overflow: auto;
    :deep(.el-upload) {
      height: 80% !important;
    }
    :deep(.el-upload-dragger) {
      height: 100% !important;
    }
  }
  .file-list {
    .file {
      &:hover {
        background-color: #f0e8f1;
      }
      & :last-child {
        cursor: pointer;
      }
    }
  }
}
</style>
